﻿// 项目：	Guan.CMS.Web - Guan.CMS
// 文件名：	ProductController.cs
// 
// 修改时间：2013-03-09 21:55
// 修改人：	Cooclsee

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using Guan.CMS.CommandProcessor.Dispatcher;
using Guan.CMS.Core.Common;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.Product;
using Guan.CMS.Model.Entities;
using Guan.CMS.Web.Core.ActionFilters;
using Guan.CMS.Web.Core.Extensions;
using Guan.CMS.Web.Core.Models;
using Guan.CMS.Web.Helpers;
using Guan.CMS.Web.ViewModels.Product;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

namespace Guan.CMS.Web.Areas.Admin.Controllers
{
    [CmsAuthorize(Roles.Admin)]
    public class ProductController : Controller
    {
        private readonly IProductRepository _productRepository;
        private readonly IProductCategoryRepository _productCategoryRepository;
        private readonly ICommandBus _commandBus;
        private const string SessionImageKey = "ProductTempCreate";
        private const string SessionFlagKey = "ProductTempCreateFlag";

        public ProductController(IProductRepository productRepository, ICommandBus commandBus, IProductCategoryRepository productCategoryRepository)
        {
            _productRepository = productRepository;
            this._productCategoryRepository = productCategoryRepository;
            _commandBus = commandBus;
        }

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            var vm = this.GetProductList().OrderByDescending(c => c.UpdatedTime);
            return View(vm);
        }

        private IEnumerable<ProductListViewModel> GetProductList()
        {
            var products = this._productRepository.GetList(true).AsEnumerable();
            var vm = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductListViewModel>>(products);
            return vm;
        }

        [HttpPost]
        public ActionResult ListAjax([DataSourceRequest] DataSourceRequest request)
        {
            var vm = this.GetProductList();
            return Json(vm.ToDataSourceResult(request));
        }

        public ActionResult Edit(int id)
        {
            Session[SessionFlagKey] = false;
            var product = _productRepository.GetById(id);
            var viewModel = Mapper.Map<Product, ProductFormModel>(product);
            var list = _productCategoryRepository.GetAll(showHidden: false).ToList();
            var vm = list.ToProductCategoryTree();
            ViewBag.CategoryId = vm;
            return View(viewModel);
        }

        [HttpPost, ActionName("Edit")]
        public ActionResult EditSave(ProductFormModel form)
        {
            var isAdd = (bool)Session[SessionFlagKey];
            if (ModelState.IsValid)
            {
                var command = Mapper.Map<ProductFormModel, AddOrUpdateProductCommand>(form);
                IEnumerable<ValidationResult> errors = _commandBus.Validate(command);
                ModelState.AddModelErrors(errors);
                if (ModelState.IsValid)
                {
                    var result = _commandBus.Submit(command);
                    if (result.Success)
                    {
                        if (isAdd)
                        {
                            //保存图片
                            var imageCommand = Session[SessionImageKey] as UploadProductImageCommand;
                            Debug.Assert(imageCommand != null, "imageCommand != null");
                            imageCommand.ProductId = (int) result.Content;
                            SaveImage(imageCommand);
                            Session.Remove(SessionFlagKey);
                            //Session.Remove(SessionImageKey);
                        }
                        return RedirectToAction("Index");
                    }
                }
            }
            return this.View(form);
        }

        public ActionResult Create()
        {
            Session[SessionFlagKey] = true;
            Session.Remove(SessionImageKey);
            var modelToCreate = new ProductFormModel {IsPublished = true};
            var list = _productCategoryRepository.GetAll(showHidden: false).ToList();
            var vm = list.ToProductCategoryTree();
            ViewBag.CategoryId = vm;
            return View("Edit",modelToCreate);
        }

        [HttpPost]
        public ActionResult Remove(List<int> id)
        {
            if (id!=null && id.Any())
            {
                var command = new RemoveProductsCommand(id);
                var result = _commandBus.Submit(command);
            }
            return RedirectToAction("List");
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public ActionResult FileSave(HttpPostedFileBase file, int? id)
        {
            if (file != null && id.HasValue)
            {
                var command = new UploadProductImageCommand(id.Value, file);
                if ((bool)Session[SessionFlagKey])
                {
                    //添加状态下，图片临时放到Session
                    Session[SessionImageKey] = command;
                }
                else{
                    SaveImage(command);
                }
                return Content(string.Empty);
            }
            return Content("上传失败！");
        }

        public ActionResult FileRemove(string fileNames)
        {
            return Content(string.Empty);
        }

        private void SaveImage(UploadProductImageCommand command)
        {
            _commandBus.Submit(command);
        }
    }
}